package czx.action;

import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import czx.action.base.BaseAction;
import czx.model.Tuser;
import czx.model.ValidateException;
import czx.pageModel.User;
import czx.service.UserServiceI;
import czx.util.Encrypt;
import czx.util.HqlExp;

@Action("userAction")
public class UserAction extends BaseAction implements ModelDriven<User> {

	private static final Logger logger = Logger.getLogger(UserAction.class);

	private UserServiceI userService;
	private User user = new User();

	public UserServiceI getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserServiceI userService) {
		this.userService = userService;
	}

	public void login() {
		HqlExp hqlExp = new HqlExp("from Tuser t where t.chname=:name");
		hqlExp.AddParam("name", user.getName());
		Tuser t = userService.get(hqlExp);
		if (t == null) {
			super.notify(false, "用户名错误!");
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String pwd = Encrypt.e(user.getPwd() + sdf.format(t.getCreatedatetime()));
			if (t.getPassword().equals(pwd)) {
				super.notify(true, "登录成功!");
			} else {
				super.notify(false, "密码错误！");
			}
		}

		if (logger.isInfoEnabled()) {
			logger.info("进入 userAction.loginTest 成功！");
		}
	}
	
	public void reg() {
		try {
			userService.add(user.getName(), user.getPwd());
			super.notify(true, "注册成功！");
		} catch (ValidateException e) {
			e.printStackTrace();
			super.notify(false, e.getMessage());
		}
	}

	@Override
	public User getModel() {
		return user;
	}
}
